<template>
    <div class="order-door-add">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="94px">
            <div class="form-content">
                <el-form-item label="自提点名称" prop="selfLiftName">
                    <el-input
                        placeholder="请输入自提点名称，不超过20个字"
                        class="w420"
                        maxlength="20"
                        v-model.trim="form.selfLiftName"
                        show-word-limit></el-input>
                </el-form-item>
                <MapTen ref="MapTenRef" :data="form" @change="onMapChange" type="door" />
                <!-- <el-form-item label="所在地区" prop="contactPhone">
                <el-cascader
                    class="w420"
                    v-model="form.value"
                    placeholder="请选择省市区"
                    :options="state.addressList"
                    :props="defaultProps"
                    @change="handleChange" />
            </el-form-item> -->
                <el-form-item label="联系人" prop="contactName">
                    <el-input
                        placeholder="请输入联系人名称"
                        class="w420"
                        maxlength="20"
                        v-model.trim="form.contactName"
                        show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactMobile">
                    <el-input placeholder="请输入联系电话" class="w420" v-model.trim="form.contactMobile"></el-input>
                </el-form-item>
                <el-form-item label="营业时间" prop="siteExtension">
                    <div class="custom-form-item">
                        <el-checkbox-group v-model="form.siteExtension">
                            <el-checkbox v-for="item in weeks" :key="item.val" :label="item.val">
                                {{ item.label }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-form-item label="" prop="time">
                    <el-time-picker
                        v-model="form.time"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        class="w440"
                        is-range
                        value-format="HH:mm"
                        format="HH:mm"
                        @visible-change="handleTimeChange"
                        @change="handleTimeChange"
                        range-separator="至" />
                </el-form-item>
            </div>
            <div class="form-footer" style="flex: auto">
                <div>
                    <el-button @click="cancelHandler()">取消</el-button>
                    <el-button type="primary" @click="saveHandler()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { reactive, ref, unref, watch, nextTick, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/request';
import storage from '@/commons/storage';
import { cloneDeep, isEmpty, isNotEmpty, format } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import MapTen from '@/components/MapTen.vue';

const router = useRouter();
const route = useRoute();

const formRef = ref();
const form = reactive({
    selfLiftName: '', // '自提点名称',
    area: [],
    provinceId: null, // '省份Id',
    cityId: null, //'城市',
    areaId: null, // '地区',
    streetId: null, //'乡镇',
    address: null, //'临时详细地址',
    street: '', //  详细地址
    lat: '', //'纬度',
    lng: '', // '经度',
    contactName: null, //'联系人姓名',
    contactMobile: '', // '联系人电话',
    siteExtension: [],
    time: null
});

const validateExtension = (rule, value, callback) => {
    if (!value || !value?.length) {
        return callback('请选择星期');
    }
    callback();
};
const validateTime = (rule, value, callback) => {
    if (!value || !value?.length || !value?.[0]) {
        return callback('请选择时间');
    }
    callback();
};
const validateAddress = (rule, value, callback) => {
    if (!value) {
        return callback('请输入详细地址');
    }
    if (!form.lat || !form.lng) {
        return callback('请选择正确的详细地址');
    }
    callback();
};
const rules = {
    selfLiftName: [{ required: true, message: '请填写自提点名称' }],
    // area: [{ required: true, message: '请选择自提点', trigger: 'change' }],
    // address: [{ required: true, message: '请输入详细地址' }, { validator: validateAddress }],
    contactName: [{ required: true, message: '请填写联系人' }],
    contactMobile: [
        { required: true, message: '请填写联系电话' },
        { pattern: /^1[3-9][0-9]{9}$/, message: '请输入正确手机号' }
    ],
    siteExtension: [{ required: true, message: '请选择星期', trigger: 'change' }, { validator: validateExtension }],
    time: [{ required: true, message: '请选择时间', trigger: 'change' }, { validator: validateTime }]
};
// const weeksEn = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
const weeks = ['一', '二', '三', '四', '五', '六', '日'].map((item, index) => {
    return {
        label: '周' + item,
        val: index + 1
    };
});

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

const handleTimeChange = () => {
    validateField('time');
};

/**
 * 取消
 */
const cancelHandler = () => {
    // router.push({ path: '/marketing/group' });
    router.back();
};

/**
 * 提交保存
 * @param {*} tableRef
 */

const saveHandler = async () => {
    // todo:接口
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            // todo:删除的id集合
            const _form = cloneDeep(form);
            if (route?.query?.id) {
                _form.siteExtensionIdsDel = _form.siteExtensionClone
                    .filter(citem => !_form.siteExtension.find(item => citem.weekTime == item))
                    .map(item => item.id);
                _form.siteExtension = _form.siteExtension.map(item => {
                    const current = _form.siteExtensionClone.find(citem => citem.weekTime == item);
                    const weekTime = current ? current.weekTime : item;
                    const id = current ? current.id : null;
                    return {
                        id,
                        weekTime,
                        timeSegmentStart: _form?.time?.[0],
                        timeSegmentEnd: _form?.time?.[1]
                    };
                });
            } else {
                _form.siteExtension = _form.siteExtension.map(item => {
                    return {
                        weekTime: item,
                        timeSegmentStart: _form?.time?.[0],
                        timeSegmentEnd: _form?.time?.[1]
                    };
                });
            }
            delete _form.area;
            delete _form.time;
            const { code } = await request(route.query.id ? 'selfLiftUpdate' : 'selfLiftCreat', _form);
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '保存成功'
            });
            cancelHandler();
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const MapTenRef = ref(null);
const onMapChange = v => {
    Object.assign(form, v);
    nextTick(() => {
        form.street && formRef?.value && formRef?.value?.validateField('street');
        form.area?.length && formRef?.value && formRef?.value?.validateField('area');
        form.lng && formRef?.value && formRef?.value?.validateField('lng');
    });
};

const getDetail = async () => {
    const { data } = await request('selfLiftInfo', { id: form.id });
    data.area = [data.provinceId, data.cityId, data.areaId];
    data.siteExtensionClone = cloneDeep(data.siteExtension);
    if (data?.siteExtension?.[0]?.timeSegmentStart) {
        data.time = [data?.siteExtension?.[0]?.timeSegmentStart, data?.siteExtension?.[0]?.timeSegmentEnd];
    }
    data.siteExtension = data.siteExtension.map(item => item.weekTime);
    Object.assign(form, data || {});
    MapTenRef.value.onShowMap(data);
};

watch(
    () => route.query.id,
    val => {
        form.id = val;
    },
    {
        immediate: true
    }
);
/* ****************************************************************** */

onMounted(() => {
    // getDetail();
    setLayout();
    if (route.query.id) {
        getDetail();
    } else {
        MapTenRef.value.onShowMap();
    }
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
.order-door-add {
    .w420 {
        width: 420px;
        max-width: 420px;
    }
    .w440 {
        width: 240px;
        max-width: 240px;
    }
}
</style>
<style lang="scss" scoped src="./add.scss"></style>
